package com.sdry.web.controller.zc;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.sdry.model.barCodeOperation.BarCodeOperation;
import com.sdry.model.lz.CodeMark;
import com.sdry.model.lz.Materiel;
import com.sdry.model.lz.WarehouseRegion;
import com.sdry.model.lz.WarehouseRegionLocation;
import com.sdry.model.zc.ZcMaterielAndTrayEntity;
import com.sdry.model.zc.ZcMaterileMoveInfoEntity;
import com.sdry.model.zc.ZcSysUserEntity;
import com.sdry.model.zc.ZcTrayAndLocationEntity;
import com.sdry.service.barCodeOperation.BarCodeOperationService;
import com.sdry.service.jyy.ReceiveDetailService;
import com.sdry.service.llm.CancellingStockDetailService;
import com.sdry.service.lz.InventoryService;
import com.sdry.service.prepare.PrepareOneService;
import com.sdry.service.zc.ZcBindAndUnbindService;
import com.sdry.utils.DateUtil;
import com.sdry.utils.ResponseUtil;

/**
 * 
 * @ClassName:    ZcBindAndUnbindController   
 * @Description:  物料与托盘的绑定与解绑
 * @Author:       zc   
 * @CreateDate:   2019年6月3日 上午9:22:20   
 * @Version:      v1.0
 */
@Controller
@RequestMapping("bindAndUnbind")
public class ZcBindAndUnbindController {

	@Resource
	private ZcBindAndUnbindService zcBindAndUnbindService;
	@Resource
	private BarCodeOperationService barCodeOperationService;
	@Resource
	private PrepareOneService prepareOneService;
	@Resource
	private ReceiveDetailService ReceiveDetailService;
	@Resource
	private InventoryService inventoryService;
	@Resource
	private CancellingStockDetailService cancellingStockDetailService;
	
	/**
	 * 进入绑定与解绑页面
	 * @return
	 */
	@RequestMapping("enterBindAndUnbindPage")
	public ModelAndView enterBindAndUnbindPage(){
		ModelAndView mav = new ModelAndView();
		mav.setViewName("/zc/warehouse/bindAndUnbind");
		return mav;
	}
	/**
	 * 通过物料条码查询物料信息
	 * @param materiel_code
	 * @param response
	 */
	@RequestMapping("selectMaterielInfoByCode")
	public void selectMaterielInfoByCode(String materiel_code,HttpServletResponse response){
		Materiel materiel = zcBindAndUnbindService.selectMaterielInfoByCode(materiel_code);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("data", materiel);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 绑定物料托盘并上架
	 * @param httpSession
	 * @param response
	 * @param zcMaterielAndTrayEntity
	 */
	@RequestMapping("bindingAndUp")
	public void bindingAndUp(HttpSession httpSession,HttpServletResponse response,ZcMaterielAndTrayEntity zcMaterielAndTrayEntity){
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		ZcSysUserEntity su = (ZcSysUserEntity)httpSession.getAttribute("user");
		zcMaterielAndTrayEntity.setBinding_person(su.getId());
		zcMaterielAndTrayEntity.setBinding_date(sdf.format(date));
		int affact = zcBindAndUnbindService.bindingAndUp(zcMaterielAndTrayEntity);
		try {
			ResponseUtil.write(response, affact);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 通过物料条码查询物料所在位置及库位详情
	 */
	@RequestMapping("selectMaterielLocationByCode")
	public void selectMaterielLocationByCode(String materiel_code,HttpServletResponse response){
		ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = zcBindAndUnbindService.selectMaterielLocationByCode(materiel_code);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("data", zcMaterielAndTrayEntity);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 下架解绑物料托盘
	 * @param httpSession
	 * @param response
	 * @param zcMaterielAndTrayEntity
	 */
	@RequestMapping("downAndUnbind")
	public void downAndUnbind(HttpSession httpSession,HttpServletResponse response,ZcMaterielAndTrayEntity zcMaterielAndTrayEntity){
		int affact = zcBindAndUnbindService.downAndUnbind(zcMaterielAndTrayEntity);
		try {
			ResponseUtil.write(response, affact);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 条件查询库位信息
	 * @param tray_code
	 */
	@RequestMapping("selectTopLocation")
	public void selectTopLocation(Materiel materiel, HttpServletResponse response){
		if(materiel.getMateriel_num()==null){
			materiel.setMateriel_num("");
		}
		if(materiel.getMateriel_size()==null){
			materiel.setMateriel_size("");
		}
		if(materiel.getMateriel_properties()==null){
			materiel.setMateriel_properties("");
		}
		List<WarehouseRegionLocation> warehouseRegionLocation = zcBindAndUnbindService.selectTopLocation(materiel);
		JSONObject jsonObject = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		JSONArray jsonArray = JSONArray.fromObject(warehouseRegionLocation, jsonConfig);
		jsonObject.put("code", 0);
		jsonObject.put("data", jsonArray);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 进入库位实时信息页面
	 */
	@RequestMapping("enterLocationRealtimeInfoPage")
	public ModelAndView enterLocationRealtimeInfoPage(Materiel materiel){
		if(materiel.getMateriel_num()==null){
			materiel.setMateriel_num("");
		}
		if(materiel.getMateriel_size()==null){
			materiel.setMateriel_size("");
		}
		if(materiel.getMateriel_properties()==null){
			materiel.setMateriel_properties("");
		}
		List<WarehouseRegionLocation> warehouseRegionLocation = zcBindAndUnbindService.selectTopLocation(materiel);
		List<WarehouseRegion> allRegion = zcBindAndUnbindService.selectAllRegion();
		ModelAndView mav = new ModelAndView();
		mav.addObject("warehouseRegionLocation",warehouseRegionLocation);
		mav.addObject("allRegion",allRegion);
		mav.setViewName("zc/warehouse/locationRealtimeInfo");
		return mav;
	}
	/*******************************************APP************************************************/
	/**
	 * 通过物料条码查询物料信息
	 * @param materiel_code
	 * @param response
	 */
	@RequestMapping("selectMaterielInfoByCodeApp")
	public void selectMaterielInfoByCodeApp(HttpServletResponse response,String materiel_code){
		String return_code=materiel_code;
		materiel_code += ",";
		String location_code = zcBindAndUnbindService.selectByMaterielCode(materiel_code);
		Materiel materiel = zcBindAndUnbindService.selectMaterielInfoByCode(materiel_code);
		//llm 查询同一物料同一批次的所有条码
		int count = 0;
		String code = materiel_code.replace(",", "");
		List<CodeMark> codes = barCodeOperationService.selectCountOnSameCodeByCode(code);
		for(CodeMark codeMark : codes){
			String location = zcBindAndUnbindService.selectByMaterielCode(codeMark.getCode() + ",");
			if("DJ".equals(location) || "HC".equals(location)){
				count += 1;
			}
		}
		JSONObject jsonObject = new JSONObject();
		if(location_code!= null && !"DJ".equals(location_code) && !"HC".equals(location_code)  && !"SY".equals(location_code)){
			jsonObject.put("status", "0");
            jsonObject.put("message", "此条码已上架");
            try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
            return;
		}else{
			Integer i = barCodeOperationService.queryStatusByCode(code);
			if(i == null){
				i = 0;
			}
			if(i == 0){
				jsonObject.put("status", "0");
	            jsonObject.put("message", "此条码未质检");
	            try {
					ResponseUtil.write(response, jsonObject);
				} catch (Exception e) {
					e.printStackTrace();
				}
	            return;
			}
		}
		if(materiel == null){
            jsonObject.put("status", "0");
            jsonObject.put("message", "查询不到此条码");
            try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
        }else{
        	jsonObject.put("status", "1");
            jsonObject.put("data", materiel.getIs_bindtray()+","+materiel.getBetter_location()+","+materiel.getId()+materiel.getPici()+","+count+","+return_code);
            try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
	}
	
	
	/**
	 * 绑定物料托盘并上架
	 * @param response
	 * @param packType 包装类型0大箱1小箱
	 * @param materiel_num	产品码	
	 * @param sizeAndPre	规格/型号	
	 * @param mBatch	批次
	 * @param materiel_code 物料精确码，多个用逗号隔开
	 * @param tray_code	托盘码
	 * @param binding_person 绑定人id
	 */
	@RequestMapping("bindingMaterielAndTrayApp")
	public void bindingMaterielAndTrayApp(HttpServletResponse response,String materiel_code,String tray_code,String location_code,String binding_person){
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = new ZcMaterielAndTrayEntity();
		Materiel materiel = zcBindAndUnbindService.selectMaterielInfoByCode(materiel_code);
		zcMaterielAndTrayEntity.setMateriel_code(materiel_code);
		zcMaterielAndTrayEntity.setTray_code(tray_code);
		zcMaterielAndTrayEntity.setBinding_person(Long.parseLong(binding_person));
		zcMaterielAndTrayEntity.setLocation_code(location_code);
		zcMaterielAndTrayEntity.setBinding_date(sdf.format(date));
		zcMaterielAndTrayEntity.setMid(materiel.getId());
		zcMaterielAndTrayEntity.setmBatch(materiel.getPici());
		zcMaterielAndTrayEntity.setIs_ng(materiel.getIs_ng());
		int affact = zcBindAndUnbindService.bindingAndUp(zcMaterielAndTrayEntity);
		JSONObject jsonObject = new JSONObject();
		if(affact > 0){
            jsonObject.put("status", "1");
            jsonObject.put("data", "提交成功");
            try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
        } else if(affact == -2) {
        	jsonObject.put("status", "0");
            jsonObject.put("message", "提交失败，请绑定同一种物料");
            try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
        } else if(affact == -3) {
        	jsonObject.put("status", "0");
            jsonObject.put("message", "提交失败，物料已经上架");
            try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
        } else if(affact == -4) {
        	jsonObject.put("status", "0");
            jsonObject.put("message", "提交失败，此物料不能上架");
            try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
        } else if(affact == -5) {
        	jsonObject.put("status", "0");
            jsonObject.put("message", "提交失败，此物料不能上架到此库区");
            try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
        } else if(affact == -6) {
        	jsonObject.put("status", "0");
            jsonObject.put("message", "提交失败,此物料为不良品，请上架到不良品区");
            try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
        }else {
        	jsonObject.put("status", "0");
            jsonObject.put("message", "提交失败");
            try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
	}
	/**
	 * 通过物料条码查询物料所在位置
	 */
	@RequestMapping("selectMaterielLocationByCodeApp")
	public void selectMaterielLocationByCodeApp(String materiel_code,HttpServletResponse response){
		materiel_code+=",";
		ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = zcBindAndUnbindService.selectMaterielLocationByCode(materiel_code);
		JSONObject jsonObject = new JSONObject();
		if(zcMaterielAndTrayEntity == null){
			jsonObject.put("status", "0");
			jsonObject.put("message", "查询不到此物料");
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			jsonObject.put("status", "1");
			jsonObject.put("data", zcMaterielAndTrayEntity);
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 通过物料条码查询物料所在位置(下架)
	 */
	@RequestMapping("selectMaterielLocationByCodeAppDown")
	public void selectMaterielLocationByCodeAppDown(String materiel_code,HttpServletResponse response){
		String materiel_code_single = materiel_code;
		//materiel_code+=",";
		ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = zcBindAndUnbindService.selectMaterielLocationByCodeDown1(materiel_code);
		JSONObject jsonObject = new JSONObject();
		if(null == zcMaterielAndTrayEntity || null == zcMaterielAndTrayEntity.getLocation_code() || "".equals(zcMaterielAndTrayEntity.getLocation_code())){
			jsonObject.put("status", "0");
			jsonObject.put("message", "此条码不存在");
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if ("HC".equals(zcMaterielAndTrayEntity.getLocation_code())) {
			jsonObject.put("status", "0");
			jsonObject.put("message", "此物料已下架");
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if ("DJ".equals(zcMaterielAndTrayEntity.getLocation_code())) {
			jsonObject.put("status", "0");
			jsonObject.put("message", "待检区不能下架");
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			Integer down_code_num = prepareOneService.selectCodemarkNumbyCode(materiel_code.replace(",", ""));
			if(down_code_num != null){
				zcMaterielAndTrayEntity.setDown_code_num(down_code_num);
			}
			jsonObject.put("status", "1");
			zcMaterielAndTrayEntity.setMateriel_code_single(materiel_code_single);
			jsonObject.put("data", zcMaterielAndTrayEntity);
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 下架解绑物料托盘
	 * @param response
	 * @param tray_code 托盘条码
	 * @param materiel_code 物料条码
	 */
	@RequestMapping("unbindMaterielAndTrayApp")
	public void unbindMaterielAndTrayApp(HttpServletResponse response,String location,String tray,String materiel_code,String unbindle_reason,String state){
		ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = new ZcMaterielAndTrayEntity();
		zcMaterielAndTrayEntity.setMateriel_code(materiel_code);
		zcMaterielAndTrayEntity.setUnbindle_reason(unbindle_reason);
		zcMaterielAndTrayEntity.setTray_code(tray);
		zcMaterielAndTrayEntity.setLocation_code(location);
		zcMaterielAndTrayEntity.setDownType(Integer.parseInt(state));
		int affact = zcBindAndUnbindService.downAndUnbind(zcMaterielAndTrayEntity);
		JSONObject jsonObject = new JSONObject();
		if(affact > 0){
            jsonObject.put("status", "1");
            jsonObject.put("data", "提交成功");
            try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
        }else if(affact == -2) {
        	jsonObject.put("status", "0");
            jsonObject.put("message", "提交失败，托盘或物料条码不正确");
            try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
        } else {
        	jsonObject.put("status", "0");
            jsonObject.put("message", "提交失败");
            try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
	}
	
	/**
	 * 区域库存的移动(上架)
	 * @param response
	 * @param downType 下架类型，1全部，2部分
	 * @param materiel_code 物料条码
	 * @param location_code 库位条码
	 * @param tray_code 托盘条码
	 * @param targetRegion 目标区域
	 * @param binding_person 人员id
	 */
	@RequestMapping("bindAndUp2SpecialAreaUp")
	public void bindAndUp2SpecialAreaUp(HttpServletResponse response, String downType, String materiel_code, String location_code, String tray_code, String targetRegion, String binding_person){
		int affact = 0;
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("message", "提交失败");
		//遍历数组
		String [] codeArr = materiel_code.split(",");
		for (String code : codeArr) {
			List<WarehouseRegionLocation> warehouseRegionLocationList = zcBindAndUnbindService.queryLocationByCode(code);
			for (WarehouseRegionLocation warehouseRegionLocation : warehouseRegionLocationList) {
				//如果匹配上
				if (warehouseRegionLocation.getLocation_num().equals(location_code)) {
					if(downType==null || "".equals(downType)){
						downType= "2";
					}
					Date date = new Date();
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = new ZcMaterielAndTrayEntity();
					if(tray_code==null || "".equals(tray_code)){
						tray_code = System.currentTimeMillis()+"";
					}
					zcMaterielAndTrayEntity.setMateriel_code(materiel_code);
					zcMaterielAndTrayEntity.setBinding_person(Long.parseLong(binding_person));
					zcMaterielAndTrayEntity.setBinding_date(sdf.format(date));
					zcMaterielAndTrayEntity.setTargetRegion(targetRegion);
					zcMaterielAndTrayEntity.setTray_code(tray_code);
					zcMaterielAndTrayEntity.setLocation_code(location_code);
					zcMaterielAndTrayEntity.setDownType(Integer.parseInt(downType));
					affact = zcBindAndUnbindService.bindAndUp2SpecialArea(zcMaterielAndTrayEntity);
					//----------------------给历史记录表插入数据   start-------------------------------------
					SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String time = format.format(new Date());
					BarCodeOperation bar = new BarCodeOperation();
					bar.setOperator(Long.parseLong(binding_person));
					bar.setOperatingTime(time);
					bar.setBarCode(materiel_code);
					bar.setLocationId(location_code);
					if("良品区".equals(targetRegion) || "不良品区".equals(targetRegion)){
						bar.setType("上架");
					}else{
						bar.setType("下架");
					}
					if(affact > 0){
						bar.setResult("成功");
					}else{
						bar.setResult("失败");
					}
					barCodeOperationService.insert(bar);
					//----------------------给历史记录表插入数据  end-------------------------------------
				} else {
					affact = -1;
					jsonObject.put("message", "查询不到此库位");
				}
			}
		}
		if(affact <= 0){
        	jsonObject.put("status", "0");
            try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
        } else {
        	jsonObject.put("status", "1");
            jsonObject.put("message", "");
            jsonObject.put("data", "提交成功");
            try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
	}
	
	/**
	 * 区域库存的移动
	 * @param response
	 * @param downType 下架类型，1全部，2部分
	 * @param materiel_code 物料条码
	 * @param location_code 库位条码
	 * @param tray_code 托盘条码
	 * @param targetRegion 目标区域
	 * @param binding_person 人员id
	 */
	@RequestMapping("bindAndUp2SpecialArea3")
	public void bindAndUp2SpecialArea3(HttpServletResponse response, String downType, String materiel_code, String location_code, String tray_code, String targetRegion,String binding_person){
		JSONObject jsonObject = new JSONObject();
		List<String> listsx = Arrays.asList(materiel_code.split(","));
		List<ZcMaterielAndTrayEntity> list = new ArrayList<>();
		for (String s:listsx){
			//根据条码查询物料托盘绑定信息
			ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = zcBindAndUnbindService.selectMaterielTrayLocationByCode(s);
			//获取托盘码
			String tray_code1 = zcMaterielAndTrayEntity.getTray_code();
			int fid = 0;
			for (int i = 0; i < list.size(); i++) {
				if(list.get(i).getTray_code().equals(tray_code1)){
					String Materiel_code = list.get(i).getMateriel_code()+s+",";
					zcMaterielAndTrayEntity.setMateriel_code(Materiel_code);
					list.remove(i);
					list.add(zcMaterielAndTrayEntity);
					fid = 1;
					break;
				}
			}
			if(fid == 0){
				zcMaterielAndTrayEntity.setMateriel_code(s+",");
				list.add(zcMaterielAndTrayEntity);
			}
		}
		for (ZcMaterielAndTrayEntity zcMaterielAndTrayEntity:list){
			String s = zcMaterielAndTrayEntity.getMateriel_code();
			//String tray_codes = zcMaterielAndTrayEntity.getTray_code();
			jsonObject = bindAndUp2SpecialAreaMethod1(response, downType, s, location_code, new Date().getTime()+"", targetRegion, binding_person,zcMaterielAndTrayEntity.getMid(),zcMaterielAndTrayEntity.getmBatch());
			String status = jsonObject.getString("status");
			if("0".equals(status)){
				break;
			}
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public JSONObject bindAndUp2SpecialAreaMethod1(HttpServletResponse response,String downType,String materiel_code,String location_code,String tray_code,String targetRegion,String binding_person,Long mid,String mBatch){
		JSONObject jsonObject = new JSONObject();
		int count=0;
		if("良品区".equals(targetRegion)){
			//查询库位码是否是良品区的
			count = zcBindAndUnbindService.selectCountGoodByLocationCode(location_code);
			if(count==0){
				jsonObject.put("status", "0");
	            jsonObject.put("message", "库位码错误");
	            return jsonObject;
			}
		}else if("不良品区".equals(targetRegion)){
			//查询库位码是否是不良品区的
			count = zcBindAndUnbindService.selectCountBadByLocationCode(location_code);
			if(count==0){
				jsonObject.put("status", "0");
	            jsonObject.put("message", "库位码错误");
	            return jsonObject;
			}
		}
		if(downType==null || "".equals(downType)){
			downType= "2";
		}
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = new ZcMaterielAndTrayEntity();
		if(tray_code==null || "".equals(tray_code)){
			tray_code = System.currentTimeMillis()+"";
		}
		zcMaterielAndTrayEntity.setMateriel_code(materiel_code);
		zcMaterielAndTrayEntity.setBinding_person(Long.parseLong(binding_person));
		zcMaterielAndTrayEntity.setBinding_date(sdf.format(date));
		zcMaterielAndTrayEntity.setTargetRegion(targetRegion);
		zcMaterielAndTrayEntity.setTray_code(tray_code);
		zcMaterielAndTrayEntity.setLocation_code(location_code);
		zcMaterielAndTrayEntity.setDownType(Integer.parseInt(downType));
		int affact = zcBindAndUnbindService.bindAndUp2SpecialArea(zcMaterielAndTrayEntity);
		
		//----------------------给历史记录表插入数据   start-------------------------------------
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = format.format(new Date());
		BarCodeOperation bar = new BarCodeOperation();
		bar.setOperator(Long.parseLong(binding_person));
		bar.setOperatingTime(time);
		bar.setBarCode(materiel_code);
		bar.setLocationId(location_code);
		bar.setBatch(mBatch);
		bar.setMaterielId(mid);
		if("良品区".equals(targetRegion) || "不良品区".equals(targetRegion)){
			bar.setType("上架");
		}else{
			bar.setType("下架");
		}
		if(affact > 0){
			bar.setResult("成功");
		}else{
			bar.setResult("失败");
		}
		barCodeOperationService.insert(bar);
		//----------------------给历史记录表插入数据  end-------------------------------------
		
		if(affact<=0){
        	jsonObject.put("status", "0");
            jsonObject.put("message", "提交失败");
            return jsonObject;
        }else{
        	jsonObject.put("status", "1");
            jsonObject.put("message", "");
            jsonObject.put("data", "提交成功");
            return jsonObject;
        }
	}
	/**
	 * 区域库存的移动
	 * @param response
	 * @param downType 下架类型，1全部，2部分
	 * @param materiel_code 物料条码
	 * @param location_code 库位条码
	 * @param tray_code 托盘条码
	 * @param targetRegion 目标区域
	 * @param binding_person 人员id
	 */
	@RequestMapping("bindAndUp2SpecialArea")
	public void bindAndUp2SpecialArea(HttpServletResponse response,String downType,String materiel_code,String location_code,String tray_code,String targetRegion,String binding_person){
		JSONObject jsonObject = new JSONObject();
		int count=0;
		if("良品区".equals(targetRegion)){
			//查询库位码是否是良品区的
			count = zcBindAndUnbindService.selectCountGoodByLocationCode(location_code);
			if(count==0){
				jsonObject.put("status", "0");
	            jsonObject.put("message", "库位码错误");
	            try {
					ResponseUtil.write(response, jsonObject);
				} catch (Exception e) {
					e.printStackTrace();
				}
	            return;
			}
		}else if("不良品区".equals(targetRegion)){
			//查询库位码是否是不良品区的
			count = zcBindAndUnbindService.selectCountBadByLocationCode(location_code);
			if(count==0){
				jsonObject.put("status", "0");
	            jsonObject.put("message", "库位码错误");
	            try {
					ResponseUtil.write(response, jsonObject);
				} catch (Exception e) {
					e.printStackTrace();
				}
	            return;
			}
		}
		if(downType==null || "".equals(downType)){
			downType= "2";
		}
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = new ZcMaterielAndTrayEntity();
		if(tray_code==null || "".equals(tray_code)){
			tray_code = System.currentTimeMillis()+"";
		}
		zcMaterielAndTrayEntity.setMateriel_code(materiel_code);
		zcMaterielAndTrayEntity.setBinding_person(Long.parseLong(binding_person));
		zcMaterielAndTrayEntity.setBinding_date(sdf.format(date));
		zcMaterielAndTrayEntity.setTargetRegion(targetRegion);
		zcMaterielAndTrayEntity.setTray_code(tray_code);
		zcMaterielAndTrayEntity.setLocation_code(location_code);
		zcMaterielAndTrayEntity.setDownType(Integer.parseInt(downType));
		int affact = zcBindAndUnbindService.bindAndUp2SpecialArea(zcMaterielAndTrayEntity);
		
		//----------------------给历史记录表插入数据   start-------------------------------------
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = format.format(new Date());
		BarCodeOperation bar = new BarCodeOperation();
		bar.setOperator(Long.parseLong(binding_person));
		bar.setOperatingTime(time);
		bar.setBarCode(materiel_code);
		bar.setLocationId(location_code);
		if("良品区".equals(targetRegion) || "不良品区".equals(targetRegion)){
			bar.setType("上架");
		}else{
			bar.setType("下架");
		}
		if(affact > 0){
			bar.setResult("成功");
		}else{
			bar.setResult("失败");
		}
		barCodeOperationService.insert(bar);
		//----------------------给历史记录表插入数据  end-------------------------------------
		
		if(affact<=0){
        	jsonObject.put("status", "0");
            jsonObject.put("message", "提交失败");
            try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
        }else{
        	jsonObject.put("status", "1");
            jsonObject.put("message", "");
            jsonObject.put("data", "提交成功");
            try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
	}
	
	
	/**
	 * 区域库存的移动
	 * @param response
	 * @param downType 下架类型，1全部，2部分
	 * @param materiel_code 物料条码
	 * @param location_code 库位条码
	 * @param tray_code 托盘条码
	 * @param targetRegion 目标区域
	 * @param binding_person 人员id
	 */
	@RequestMapping("bindAndUp2SpecialArea2")
	public void bindAndUp2SpecialArea2(HttpServletResponse response,String downType,String materiel_code,String location_code,String tray_code,String targetRegion,String binding_person){
		JSONObject jsonObject = new JSONObject();
		downType = "2";
		List<String> listsx = Arrays.asList(materiel_code.split(","));
		List<ZcMaterielAndTrayEntity> list = new ArrayList<>();
		for (String s:listsx){
			ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = zcBindAndUnbindService.selectMaterielTrayLocationByCode(s);
			String tray_code1 = zcMaterielAndTrayEntity.getTray_code();
			int fid = 0;
			for (int i = 0; i < list.size(); i++) {
				if(list.get(i).getTray_code().equals(tray_code1)){
					String Materiel_code = list.get(i).getMateriel_code()+","+s;
					zcMaterielAndTrayEntity.setMateriel_code(Materiel_code);
					list.remove(i);
					list.add(zcMaterielAndTrayEntity);
					fid = 1;
					break;
				}
			}
			if(fid == 0){
				zcMaterielAndTrayEntity.setMateriel_code(s);
				list.add(zcMaterielAndTrayEntity);
			}
		}
		for (ZcMaterielAndTrayEntity zcMaterielAndTrayEntity:list){
			//location_code = zcMaterielAndTrayEntity.getLocation_code();
			String s = zcMaterielAndTrayEntity.getMateriel_code();
			location_code = zcMaterielAndTrayEntity.getLocation_code();
			jsonObject = bindAndUp2SpecialAreaMethod( response, downType, s, location_code, tray_code, targetRegion, binding_person,zcMaterielAndTrayEntity.getMid(),zcMaterielAndTrayEntity.getmBatch());
			String status = jsonObject.getString("status");
			if("0".equals(status)){
				break;
			}
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 区域库存的移动22
	 * @param response
	 * @param downType 下架类型，1全部，2部分
	 * @param materiel_code 物料条码
	 * @param location_code 库位条码
	 * @param tray_code 托盘条码
	 * @param targetRegion 目标区域
	 * @param binding_person 人员id
	 */
	public JSONObject bindAndUp2SpecialAreaMethod(HttpServletResponse response,String downType,String materiel_code,String location_code,String tray_code,String targetRegion,String binding_person,Long mid,String mBatch){
		JSONObject jsonObject = new JSONObject();
		int count=0;
		if("良品区".equals(targetRegion)){
			//查询库位码是否是良品区的
			count = zcBindAndUnbindService.selectCountGoodByLocationCode(location_code);
			if(count==0){
				jsonObject.put("status", "0");
	            jsonObject.put("message", "库位码错误");
	            return jsonObject;
			}
		}else if("不良品区".equals(targetRegion)){
			//查询库位码是否是不良品区的
			count = zcBindAndUnbindService.selectCountBadByLocationCode(location_code);
			if(count==0){
				jsonObject.put("status", "0");
	            jsonObject.put("message", "库位码错误");
	            return jsonObject;
			}
		}
		if(downType==null || "".equals(downType)){
			downType= "2";
		}
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = new ZcMaterielAndTrayEntity();
		if(tray_code==null || "".equals(tray_code)){
			tray_code = System.currentTimeMillis()+"";
		}
		zcMaterielAndTrayEntity.setMateriel_code(materiel_code);
		zcMaterielAndTrayEntity.setBinding_person(Long.parseLong(binding_person));
		zcMaterielAndTrayEntity.setBinding_date(sdf.format(date));
		zcMaterielAndTrayEntity.setTargetRegion(targetRegion);
		zcMaterielAndTrayEntity.setTray_code(tray_code);
		zcMaterielAndTrayEntity.setLocation_code(location_code);
		zcMaterielAndTrayEntity.setDownType(Integer.parseInt(downType));
//		int affact = zcBindAndUnbindService.bindAndUp2SpecialArea(zcMaterielAndTrayEntity);
		int affact = soldOut(zcMaterielAndTrayEntity);
		//----------------------给历史记录表插入数据   start-------------------------------------
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = format.format(new Date());
		BarCodeOperation bar = new BarCodeOperation();
		bar.setOperator(Long.parseLong(binding_person));
		bar.setOperatingTime(time);
		bar.setBarCode(materiel_code);
		bar.setLocationId(location_code);
		bar.setBatch(mBatch);
		bar.setMaterielId(mid);
		if("良品区".equals(targetRegion) || "不良品区".equals(targetRegion)){
			bar.setType("上架");
		}else{
			bar.setType("下架");
		}
		if(affact > 0){
			bar.setResult("成功");
		}else{
			bar.setResult("失败");
		}
		barCodeOperationService.insert(bar);
		//----------------------给历史记录表插入数据  end-------------------------------------
		if(affact<=0){
        	jsonObject.put("status", "0");
            jsonObject.put("message", "提交失败");
        }else{
        	jsonObject.put("status", "1");
            jsonObject.put("message", "");
            jsonObject.put("data", "提交成功");
        }
		return jsonObject;
	}
	
	/**
	 * llm 下架
	 * @Title:soldOut   
	 * @return
	 */
	public int soldOut(ZcMaterielAndTrayEntity zcMaterielAndTrayEntity){
		int up = 0;
		String [] split = zcMaterielAndTrayEntity.getMateriel_code().split(",");
		ZcMaterielAndTrayEntity zcMaterielAndTrayEntity2 = new ZcMaterielAndTrayEntity();
		String tray_code = System.currentTimeMillis()+"";
		//一、、从原来位置下架
		//如果是全部下架
		if(zcMaterielAndTrayEntity.getDownType() == 1){
			//根据库位查询所有托盘
			ZcTrayAndLocationEntity a = new ZcTrayAndLocationEntity();
			a.setLocation_code(zcMaterielAndTrayEntity.getLocation_code());
			ZcTrayAndLocationEntity zcTrayAndLocationEntityOld = zcBindAndUnbindService.selectTrayCodeByLocationCode(a);
			if(zcTrayAndLocationEntityOld != null){
				String [] trays = zcTrayAndLocationEntityOld.getTray_code().split(",");
				for(String tray : trays){
					//删除每个托盘
					inventoryService.deleteByCode("tray_code", tray, "zc_materiel_tray");
				}
				//删除库位
				inventoryService.deleteByCode("location_code", zcMaterielAndTrayEntity.getLocation_code(), "zc_tray_location");
			}
			zcMaterielAndTrayEntity2.setTray_code(zcMaterielAndTrayEntity.getTray_code());
			zcMaterielAndTrayEntity2.setMateriel_code(zcMaterielAndTrayEntity.getMateriel_code());
			up = up(tray_code,zcMaterielAndTrayEntity2, split);
		//如果是部分下架
		}else{
			//根据物料码找托盘信息
			zcMaterielAndTrayEntity2 = ReceiveDetailService.queryMaterielTrayByCode(split[0]);
			String materiel_code = zcMaterielAndTrayEntity2.getMateriel_code();
			int num = 0;
			for(String materielCode : split){
				//1、用空字符串替换每个条码
				materiel_code = materiel_code.replace(materielCode + ",", "");
				//2、如果替换后物料条码为空，删除这条数据
				if(materiel_code.length() == 0){
					deleteMaterielAndTray(zcMaterielAndTrayEntity2.getId(), zcMaterielAndTrayEntity2.getTray_code());
				}else{
					//3、修改数据
					inventoryService.updateById(zcMaterielAndTrayEntity2.getId()+"", "materiel_code", materiel_code, "zc_materiel_tray");
					CodeMark ck = cancellingStockDetailService.queryCodeByCode(materielCode);
					if(num == 0){
						num = zcMaterielAndTrayEntity2.getmNum() - ck.getNum();
					}else{
						num = num - ck.getNum();
					}
					if(num > 0){
						inventoryService.updateById(zcMaterielAndTrayEntity2.getId()+"", "mNum", num+"", "zc_materiel_tray");
					}else{
						ReceiveDetailService.deleteMaterielTrayById(zcMaterielAndTrayEntity2.getId());
					}
				}
			}
			//zcMaterielAndTrayEntity2.setMateriel_code(materiel_code+",");
			zcMaterielAndTrayEntity2.setMateriel_code(zcMaterielAndTrayEntity.getMateriel_code());
			up = up(tray_code,zcMaterielAndTrayEntity2, split);
		}
		return up;
	}
	
	
	public int up(String tray_code,ZcMaterielAndTrayEntity zcMaterielAndTrayEntity, String[] split){
		int i = 0;
		//二、在缓存区上架
		//1、在物料和托盘关系表新增记录
		int sum = 0;
		for (String codeMark2 : split) {
			CodeMark ck = cancellingStockDetailService.queryCodeByCode(codeMark2);
			sum += ck.getNum();
		}
		
		zcMaterielAndTrayEntity.setMateriel_code(zcMaterielAndTrayEntity.getMateriel_code()+",");
		zcMaterielAndTrayEntity.setmNum(sum);
		zcMaterielAndTrayEntity.setTray_code(tray_code);
		i = inventoryService.MaterielTrayInsert(zcMaterielAndTrayEntity);
		ZcMaterileMoveInfoEntity zcMaterileMoveInfoEntity = new ZcMaterileMoveInfoEntity();
		zcMaterileMoveInfoEntity.setMid(zcMaterielAndTrayEntity.getMid());
		zcMaterileMoveInfoEntity.setNum(zcMaterielAndTrayEntity.getmNum());
		zcMaterileMoveInfoEntity.setPici(zcMaterielAndTrayEntity.getmBatch());
		zcMaterileMoveInfoEntity.setEnterPerson(zcMaterielAndTrayEntity.getBinding_person());
		zcMaterileMoveInfoEntity.setEnterDate(DateUtil.dateFormat3());
		
		//记录下架记录
		for (String codeMark2 : split) {
			ZcMaterielAndTrayEntity zcMaterielAndTrayEntity1 = zcMaterielAndTrayEntity;
			zcMaterielAndTrayEntity1 .setMateriel_code(codeMark2);
			zcBindAndUnbindService.insertUnbindleRecord(zcMaterielAndTrayEntity1);
		}
		//缓存区添加库存
		int inCache = zcBindAndUnbindService.inCache(zcMaterileMoveInfoEntity);
		int outGood = zcBindAndUnbindService.outGood(zcMaterileMoveInfoEntity);
		//2、根据缓存区库位查询数据
		ZcTrayAndLocationEntity a = new ZcTrayAndLocationEntity();
		a.setLocation_code("HC");
		ZcTrayAndLocationEntity zcTrayAndLocationEntityOld = zcBindAndUnbindService.selectTrayCodeByLocationCode(a);
		//3、如果不为空，修改数据
		if(zcTrayAndLocationEntityOld != null){
			String trayCodes = zcTrayAndLocationEntityOld.getTray_code() + zcMaterielAndTrayEntity.getTray_code() + ",";
			inventoryService.updateById(zcTrayAndLocationEntityOld.getId()+"", "tray_code", trayCodes, "zc_tray_location");
		}else{
			//4、新增库位
			ZcTrayAndLocationEntity zcTrayAndLocationEntity = new ZcTrayAndLocationEntity();
			//托盘码
			zcTrayAndLocationEntity.setTray_code(tray_code);
			//库区编码
			zcTrayAndLocationEntity.setLocation_code("HC");
			//绑定人
			zcTrayAndLocationEntity.setBinding_person(zcMaterielAndTrayEntity.getBinding_person());
    		//绑定时间
			zcTrayAndLocationEntity.setBinding_date(zcMaterielAndTrayEntity.getBinding_date());
			 i = inventoryService.trayLocationInsert(zcTrayAndLocationEntity);
		}
		return i;
	}
	
	/**
	 * 删除托盘号
	 * @param id
	 * @param trayCode
	 */
	public void deleteMaterielAndTray(Long id, String trayCode){
		//1、删除这个记录
		ReceiveDetailService.deleteMaterielTrayById(id);
		//2、根据托盘号查询库位数据信息
		ZcTrayAndLocationEntity queryTrayLocationByTray = ReceiveDetailService.queryTrayLocationByTray(trayCode);
		//3、把托盘号用“”代替
		String trays = queryTrayLocationByTray.getTray_code().replace(trayCode+",", "");
		//4、如果替换后托盘码字符串为空，删除这条记录
		if(trays.length() == 0){
			inventoryService.deleteById(queryTrayLocationByTray.getId()+"", "zc_tray_location");
		}else{
			//5、否则修改数据
			inventoryService.updateById(queryTrayLocationByTray.getId()+"", "tray_code", trays, "zc_tray_location");
		}
	}
}
